// 嫌疑人数据服务类
import { SuspectModel, SuspicionLevel, Gender } from '../model/SuspectModel';
import { FileIOMock } from '../../mocks/fileioMock';

export class SuspectService {
  private static readonly FILE_PATH = 'suspects.json';
  
  /**
   * 获取所有嫌疑人
   * @returns 嫌疑人列表
   */
  public static async getAllSuspects(): Promise<SuspectModel[]> {
    try {
      const suspects = await FileIOMock.readJSONFile(this.FILE_PATH);
      return suspects.map((item: any) => SuspectModel.fromJson(item));
    } catch (error) {
      console.error('Failed to get all suspects:', error);
      return [];
    }
  }
  
  /**
   * 根据ID获取嫌疑人
   * @param id 嫌疑人ID
   * @returns 嫌疑人对象，如果不存在返回null
   */
  public static async getSuspectById(id: string): Promise<SuspectModel | null> {
    try {
      const suspects = await this.getAllSuspects();
      const suspect = suspects.find(item => item.getId() === id);
      return suspect || null;
    } catch (error) {
      console.error(`Failed to get suspect by id ${id}:`, error);
      return null;
    }
  }
  
  /**
   * 根据案件ID获取嫌疑人列表
   * @param caseId 案件ID
   * @returns 嫌疑人列表
   */
  public static async getSuspectsByCaseId(caseId: string): Promise<SuspectModel[]> {
    try {
      const suspects = await this.getAllSuspects();
      return suspects.filter(item => item.getCaseId() === caseId);
    } catch (error) {
      console.error(`Failed to get suspects by case id ${caseId}:`, error);
      return [];
    }
  }
  
  /**
   * 添加新嫌疑人
   * @param suspectModel 嫌疑人对象
   * @returns 是否添加成功
   */
  public static async addSuspect(suspectModel: SuspectModel): Promise<boolean> {
    try {
      // 设置唯一ID
      if (!suspectModel.getId()) {
        suspectModel.setId(SuspectModel.generateId());
      }
      
      const suspects = await this.getAllSuspects();
      suspects.push(suspectModel);
      
      // 将所有嫌疑人对象转换为JSON并保存
      const suspectsJson = suspects.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, suspectsJson);
    } catch (error) {
      console.error('Failed to add suspect:', error);
      return false;
    }
  }
  
  /**
   * 更新嫌疑人
   * @param suspectModel 更新后的嫌疑人对象
   * @returns 是否更新成功
   */
  public static async updateSuspect(suspectModel: SuspectModel): Promise<boolean> {
    try {
      const suspects = await this.getAllSuspects();
      const index = suspects.findIndex(item => item.getId() === suspectModel.getId());
      
      if (index === -1) {
        return false; // 嫌疑人不存在
      }
      
      // 更新嫌疑人
      suspects[index] = suspectModel;
      
      // 将所有嫌疑人对象转换为JSON并保存
      const suspectsJson = suspects.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, suspectsJson);
    } catch (error) {
      console.error(`Failed to update suspect ${suspectModel.getId()}:`, error);
      return false;
    }
  }
  
  /**
   * 删除嫌疑人
   * @param id 嫌疑人ID
   * @returns 是否删除成功
   */
  public static async deleteSuspect(id: string): Promise<boolean> {
    try {
      const suspects = await this.getAllSuspects();
      const filteredSuspects = suspects.filter(item => item.getId() !== id);
      
      if (filteredSuspects.length === suspects.length) {
        return false; // 嫌疑人不存在
      }
      
      // 将过滤后的嫌疑人对象转换为JSON并保存
      const suspectsJson = filteredSuspects.map(item => item.toJson());
      return await FileIOMock.writeJSONFile(this.FILE_PATH, suspectsJson);
    } catch (error) {
      console.error(`Failed to delete suspect ${id}:`, error);
      return false;
    }
  }
  
  /**
   * 根据嫌疑程度获取嫌疑人
   * @param level 嫌疑程度
   * @returns 符合条件的嫌疑人列表
   */
  public static async getSuspectsBySuspicionLevel(level: SuspicionLevel): Promise<SuspectModel[]> {
    try {
      const suspects = await this.getAllSuspects();
      return suspects.filter(item => item.getSuspicionLevel() === level);
    } catch (error) {
      console.error(`Failed to get suspects by suspicion level ${level}:`, error);
      return [];
    }
  }
  
  /**
   * 根据性别获取嫌疑人
   * @param gender 性别
   * @returns 符合条件的嫌疑人列表
   */
  public static async getSuspectsByGender(gender: Gender): Promise<SuspectModel[]> {
    try {
      const suspects = await this.getAllSuspects();
      return suspects.filter(item => item.getGender() === gender);
    } catch (error) {
      console.error(`Failed to get suspects by gender ${gender}:`, error);
      return [];
    }
  }
  
  /**
   * 搜索嫌疑人
   * @param keyword 搜索关键词
   * @returns 符合条件的嫌疑人列表
   */
  public static async searchSuspects(keyword: string): Promise<SuspectModel[]> {
    try {
      const suspects = await this.getAllSuspects();
      const lowerKeyword = keyword.toLowerCase();
      
      return suspects.filter(item => 
        item.getName().toLowerCase().includes(lowerKeyword) ||
        item.getDescription().toLowerCase().includes(lowerKeyword) ||
        item.getLastSeenLocation().toLowerCase().includes(lowerKeyword) ||
        item.getOccupation().toLowerCase().includes(lowerKeyword)
      );
    } catch (error) {
      console.error(`Failed to search suspects with keyword ${keyword}:`, error);
      return [];
    }
  }
  
  /**
   * 获取指定年龄范围的嫌疑人
   * @param minAge 最小年龄
   * @param maxAge 最大年龄
   * @returns 符合条件的嫌疑人列表
   */
  public static async getSuspectsByAgeRange(minAge: number, maxAge: number): Promise<SuspectModel[]> {
    try {
      const suspects = await this.getAllSuspects();
      return suspects.filter(item => 
        item.getAge() >= minAge && item.getAge() <= maxAge
      );
    } catch (error) {
      console.error(`Failed to get suspects by age range ${minAge}-${maxAge}:`, error);
      return [];
    }
  }
}